document.addEventListener('DOMContentLoaded', function() {
    // 图像生成相关元素
    const generateBtn = document.querySelector('.generate-btn');
    const promptInput = document.querySelector('.generation-input textarea');
    const sizeSelect = document.querySelector('select[name="image-size"]');
    const generationResult = document.querySelector('.generation-result');
    const generatedImage = document.querySelector('.generated-image img');
    const downloadBtn = document.querySelector('.download-btn');
    const statusSpan = document.querySelector('.generation-info .status');
    const timeSpan = document.querySelector('.generation-info .time');

    // 生成按钮点击事件
    generateBtn.addEventListener('click', async function() {
        const prompt = promptInput.value.trim();
        if (!prompt) {
            alert('请输入图像描述文本');
            return;
        }

        try {
            // 显示加载状态
            generateBtn.disabled = true;
            generateBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 检索中...';
            generationResult.classList.add('loading');
            statusSpan.textContent = '正在检索...';
            
            const startTime = Date.now();

            // 调用API生成图像
            const response = await fetch('https://ai.gitee.com/v1/images/generations', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer MBJWASWXHAXXUWNXMJTIRS6M7HEAMPMGUPC3Z8JI',
                    'X-Package': '1910'
                },
                body: JSON.stringify({
                    model: "HunyuanDiT-v1.2-Diffusers-Distilled",
                    size: sizeSelect.value,
                    guidance_scale: 6,
                    num_inference_steps: 35,
                    prompt: prompt
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            console.log('API响应数据:', data); // 调试日志

            // 计算生成时间
            const generateTime = ((Date.now() - startTime) / 1000).toFixed(1);

            // 显示生成结果
            if (data && data.data && Array.isArray(data.data) && data.data.length > 0) {
                // 假设返回的是base64图片数据
                const imageData = data.data[0];
                console.log('图片数据:', imageData); // 调试日志

                // 先显示结果容器
                generationResult.style.display = 'block';
                
                // 设置图片加载事件
                generatedImage.onload = function() {
                    console.log('图片加载成功');
                    statusSpan.textContent = '检索成功';
                    timeSpan.textContent = `用时：${generateTime}秒`;
                    generationResult.classList.remove('loading');
                };

                generatedImage.onerror = function() {
                    console.error('图片加载失败');
                    statusSpan.textContent = '图片加载失败';
                    alert('图片加载失败，请检查网络连接');
                };

                // 设置图片源
                // 如果返回的是base64数据
                if (typeof imageData === 'string' && imageData.startsWith('data:image')) {
                    generatedImage.src = imageData;
                }
                // 如果返回的是对象且包含b64_json字段
                else if (imageData.b64_json) {
                    generatedImage.src = `data:image/png;base64,${imageData.b64_json}`;
                }
                // 如果返回的是对象且包含url字段
                else if (imageData.url) {
                    generatedImage.src = imageData.url;
                }
                else {
                    throw new Error('不支持的图片数据格式');
                }

                // 启用下载按钮
                downloadBtn.disabled = false;
                downloadBtn.onclick = () => downloadImage(generatedImage.src);
            } else {
                console.error('API响应格式不正确:', data);
                throw new Error('API返回数据格式不正确');
            }
        } catch (error) {
            console.error('图像检索失败:', error);
            statusSpan.textContent = '检索失败';
            alert('图像检索失败，请稍后重试\n错误信息：' + error.message);
        } finally {
            // 恢复按钮状态
            generateBtn.disabled = false;
            generateBtn.innerHTML = '<i class="fas fa-magic"></i> 检索图像';
        }
    });

    // 下载图像函数
    async function downloadImage(url) {
        try {
            statusSpan.textContent = '正在下载...';
            let imageBlob;
            
            if (url.startsWith('data:')) {
                // 如果是base64数据
                const base64Data = url.split(',')[1];
                const binaryString = window.atob(base64Data);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                imageBlob = new Blob([bytes], { type: 'image/png' });
            } else {
                // 如果是URL
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                imageBlob = await response.blob();
            }

            const downloadUrl = window.URL.createObjectURL(imageBlob);
            const a = document.createElement('a');
            a.href = downloadUrl;
            a.download = 'generated-image.png';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(downloadUrl);
            statusSpan.textContent = '下载完成';
        } catch (error) {
            console.error('下载失败:', error);
            statusSpan.textContent = '下载失败';
            alert('图像下载失败，请稍后重试\n错误信息：' + error.message);
        }
    }
}); 